package pe.sonrisas.tools.view;

import Complementos.Conexion_BD;
import Complementos.Sesion;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class frmLogin extends javax.swing.JFrame {
Conexion_BD co=new Conexion_BD();
    public frmLogin() {
        initComponents();
        lblMensaje.setVisible(false);
        
        /* Obtener nombre de frm*/
//        String frm = this.getClass().getName();
//        int cortar = frm.indexOf(".");
//        System.out.println(""+frm.substring(cortar+1));
       
    }

   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtLogin = new javax.swing.JTextField();
        btnIngresar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtClave = new javax.swing.JPasswordField();
        lblMensaje = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("..::  Sonrisas Tools :..   Login");

        jPanel1.setBackground(new java.awt.Color(204, 204, 240));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Login", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 24), new java.awt.Color(255, 255, 102))); // NOI18N

        btnIngresar.setText("Ingresar");
        btnIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarActionPerformed(evt);
            }
        });

        jLabel1.setText("Ingrese usuario:");

        jLabel2.setText("Ingrese clave:");

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/sonrisas/tools/imagenes/comun/login.png"))); // NOI18N

        txtClave.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtClaveKeyPressed(evt);
            }
        });

        lblMensaje.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lblMensaje.setForeground(new java.awt.Color(255, 0, 0));
        lblMensaje.setText("jLabel4");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(67, 67, 67)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtClave)
                            .addComponent(txtLogin)
                            .addComponent(btnIngresar, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))
                        .addGap(51, 51, 51)
                        .addComponent(jLabel3))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(182, 182, 182)
                        .addComponent(lblMensaje)))
                .addContainerGap(86, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnIngresar)
                .addGap(18, 18, 18)
                .addComponent(lblMensaje)
                .addGap(12, 12, 12))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(jLabel3)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
        if (login()){
               dispose();              
                }
            else{
          txtLogin.requestFocus();
            txtLogin.selectAll();  
            }
    }//GEN-LAST:event_btnIngresarActionPerformed

    private void txtClaveKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtClaveKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER)
           if (login()){
               dispose();              
                }else
                    {
            txtLogin.requestFocus();
            txtLogin.selectAll();
                    }
    }//GEN-LAST:event_txtClaveKeyPressed

    
    public boolean login(){
        boolean login = false;    
        
        try {
            
            co.Conectar();
           ResultSet rs = null;
           String query = "SELECT count(usuario),u.idUsuario,u.usuario,p.nombres,pe.nombre "
                   + "FROM usuario u,persona p,perfil pe  "
                   + "WHERE usuario = '"+txtLogin.getText()+"'"+" "
                   + "AND clave='"+txtClave.getText()+"' "
                   + "AND u.idPERSONA = p.idPERSONA "
                   + "AND u.idPerfil = pe.id";
           
           
           rs = co.Consultar(query);       
           rs.next();
        if ( Integer.parseInt(rs.getString(1)) == 1){
                Sesion.ID_PERFIL        = rs.getInt("idUsuario");
                Sesion.LOGIN            = rs.getString("usuario");
                Sesion.NOMBRE_USUARIO   = rs.getString("p.nombres");
                Sesion.NOMBRE_PERFIL    = rs.getString("pe.nombre");
                obtenerPrivilegiosDeUsuario(Sesion.ID_PERFIL);
                
                main m=new main();
                m.setVisible(true);
                login = true;
                rs.close();
           }   
           else
           {
                lblMensaje.setText("Usuario / Password incorrecto");
                lblMensaje.setVisible(true);
                rs.close();
           }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        finally{
            try {
                co.Desconectar();
                
            } catch (Exception ex) {
                Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
            }
                
            
            }
        
        return login;
 
    } //Fin login()
    
    
    public void obtenerPrivilegiosDeUsuario(int idPerfil){
          
        try {
                co.Conectar();
                ResultSet rs = null;
                String query = "select pe.nombre, it.nombreOpcion,it.nombreArchivo, pr.ver, pr.editar, pr.crear, pr.borrar, pr.imprimir from  privilegio pr, perfil pe, item it where pr.Perfil_id ="+idPerfil+"  and it.id = pr.Item_id and pr.Perfil_id = pe.id";
                rs =  co.Consultar(query);
                
                int fila = 0;
                
                while (rs.next()){
                            Map privilegio = new HashMap();
                            privilegio.put("perfil"     ,       rs.getString("pe.nombre"));
                            privilegio.put("item"       ,       rs.getString("it.nombreOpcion"));
                            privilegio.put("archivo"    ,       rs.getString("it.nombreArchivo"));
                            privilegio.put("ver"        ,       rs.getString("pr.ver"));
                            privilegio.put("editar"     ,       rs.getString("pr.editar"));
                            privilegio.put("crear"      ,       rs.getString("pr.crear"));
                            privilegio.put("borrar"     ,       rs.getString("pr.borrar"));
                            privilegio.put("imprimir"   ,       rs.getString("pr.imprimir"));
                            Sesion.privilegios.add(privilegio);
                        }
            /*for (Map datos : Sesion.privilegios) {
                    System.out.println(datos.get("perfil") + " - "
                    + datos.get("item"));
                                                }
                                                */
             } catch (Exception e) {
                    System.out.println(""+e.getMessage());
        }
            
            
            
            
            
        //return null;
    }
    
    
    
    
    
    
    
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new frmLogin().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnIngresar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblMensaje;
    private javax.swing.JPasswordField txtClave;
    private javax.swing.JTextField txtLogin;
    // End of variables declaration//GEN-END:variables
}
